//app.js

var util = require('utils/util.js');
//app.js
var development = 'pro'; //开发版本  pro：生产  dev：开发

App({
  d: {
    hostUrl: (development == 'pro') ? 'https://www.jiugell.com/index.php?s=' : 'https://api.zjwoo.com/',
    hostImg: (development == 'pro') ? 'http://dboss.jiugell.com/' : 'http://jiugeyy.zjwoo.com/',
    hostVideo: (development == 'pro') ? 'https://www.jiugell.com/api/' : 'http://jiugeyy.zjwoo.com/',
    appId: "",
    appKey: "",
    mchnt:"5b3a1ffa803de"
  },

  onLaunch: function () {
    var that = this;
    //检测网络
    wx.getNetworkType({
      success: function(res) {
        console.log(res);
        if (res.networkType == 'none'){
          wx.showModal({
            title: '提示',
            showCancel:false,
            content: '当前网络环境较差，请检查网络',
          })
        }
        return;
      }
    })

    //小程序初始化先判断用户是否登录    
    wx.checkSession({
      success: function () {
        console.log(' ==> 当前在登录中 ');
        var sk = wx.getStorageSync('sk');
        if (!sk){
          console.log('==> sk缓存不存在')
          that.login();
          return;
        }else{
          util.req(getApp().d.hostUrl + 'api/car/vaild_sk', { "sk": sk }, function (data) {
            if (data.code == 1) {
              console.log('==> 检测 sk same')
              that.globalData.sk = sk;
              wx.setStorageSync('sk', sk);
            } else {
              console.log('==> 检测 sk no same')
              that.login();
              return;
            }
          })
        }
      },
      fail: function () {
        console.log('登录态过期,重新登录...')
        //登录态过期
        that.login() //重新登录
      }
    })
  },


  login:function(){
    console.log('----登录---')
    var that = this;
    // 登录
    wx.login({
      success: res => {
        //发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          //获取openid接口  
          url: getApp().d.hostUrl +'api/car/get_session_key',
          data: {
            js_code: res.code,
            grant_type: 'authorization_code'
          },
          header:{'mchnt': getApp().d.mchnt },
          method: 'POST',
          success: function (res) {
            console.log(res);
            if (res.data.code == 1) {
              console.log(res.data)
              wx.setStorageSync('uid', res.data.data.uid);
              wx.setStorageSync('openid', res.data.data.openid);
              wx.setStorageSync('sk', res.data.data.sk);

              that.globalData.uid = res.data.data.uid;
              that.globalData.openid = res.data.data.openid;
              that.globalData.sk = res.data.data.sk;

              console.log('登录之后:uid =>' + that.globalData.uid);

              //获取用户信息
              wx.getSetting({
                success: res => {
                  if (res.authSetting['scope.userInfo']) {
                    console.log('已授权')
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                      success: res => {
                        // 可以将 res 发送给后台解码出 unionId
                        that.globalData.userInfo = res.userInfo;
                        wx.setStorageSync('userInfo', res.userInfo);

                        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                        // 所以此处加入 callback 以防止这种情况
                        if (that.userInfoReadyCallback) {
                          that.userInfoReadyCallback(res)
                        }
                      }
                    })
                  } else {
                    console.log('未授权')
                  }
                  //console.log(this.globalData.userInfo);
                }
              })
            } else {
              wx.showToast({
                title: res.data.message,
              })
              return;
            }
          },
          fail:function(){
            that.loginFail();
          }
        })
      }
    })
  },


  loginFail: function () {
    var that = this;
    wx.showModal({
      content: '登录失败，请允许获取用户信息,如不显示请删除小程序重新进入',
      showCancel: false
    });
    that.login();
  },
  
  globalData: {
    userInfo: null,
    uid:0,
    openid:'',
    sk:''
  }
})